angular.module('mamApp').controller('albumEditController', ['$scope', '$state', '$uibModal', 'FileUploader', 'api', 'AlbumManager', '$filter', 'ChannelManager','BaseValidations','ImsErr',
    function ($scope, $state, $uibModal, FileUploader, api, AlbumManager, $filter, ChannelManager,BaseValidations,ImsErr) {
        $scope.BaseValidations=BaseValidations;
        $scope.formData = {};
        $scope.disabled = false;
        $scope.commonTagsSelected = [];
        $scope.specialTagsSelected = [];
        $scope.categorySelected = [];
        $scope.channelSelected = [];
        $scope.albumForm={};
        $scope.list=[];
        $scope.image_a = false;
        var albumId = $state.params.albumId;

        AlbumManager.albumDetail(albumId).then(function (result) {
            $scope.formData = result.data.cpAlbumVO;
            $scope.formData.keyword = $scope.formData.keyword.join(",");
            var tmpComm = [];
            var tmpSpe = [];
            $scope.categoryChange({categoryId: $scope.formData.categoryId});
            $scope.channelChange({channelId: $scope.formData.channelId})

            $scope.formData.commList.forEach(function (tag) {
                tmpComm.push({
                    commtagId: tag.commtagId,
                    dimensionId: tag.dimensionId,
                    commtagName: tag.commtagName
                })
            })
            $scope.formData.specialList.forEach(function (tag) {
                tmpSpe.push({
                    specialId: tag.specialId,
                    dimensionId: tag.dimensionId,
                    specialName: tag.specialName
                })
            })
            $scope.commonTagsSelected = tmpComm;
            $scope.specialTagsSelected = tmpSpe;
            ChannelManager.categoriesList().then(function (result) {

                $scope.categories = result.data.list;
                $scope.categorySelected = $filter('filter')($scope.categories, {categoryId: $scope.formData.categoryId})[0];
            })
        })
        $scope.channelChange = function (channel) {
            $scope.formData.channelId = channel.channelId;
            $scope.specialTagsList(channel.channelId);

        }


        $scope.categoryChange = function (category) {
            ChannelManager.channelsList(category.categoryId).then(function (result) {
                $scope.channels = result.data.list;
                $scope.channelSelected = $filter('filter')($scope.channels, {channelId: $scope.formData.channelId})[0];
            })
        }


        $scope.channelChange = function (channel) {
            $scope.specialTagsSelected = [];
            if (channel) {
                $scope.formData.channelId = channel.channelId;
                $scope.specialTagsList(channel.channelId);

            }


        }

        ChannelManager.commTagsList().then(function (result) {
            $scope.commonTags = [];
            $scope.commonDimensionsName = {};
            result.data.list.forEach(function (item) {
                $scope.commonDimensionsName[item.dimensionId] = item.dimensionsName;
                if (item.hasOwnProperty("list")) {
                    item.list.forEach(function (tag) {
                        $scope.commonTags.push({
                            commtagId: tag.commtagId,
                            dimensionId: item.dimensionId,
                            commtagName: tag.commtagName
                        })
                    })
                }
            })


        })
        /**
         * 通用标签分组
         * @param item
         * @returns {*}
         */

        $scope.commGroupFn = function (item) {
            return $scope.commonDimensionsName[item.dimensionId]
        };
        /**
         * 通用标签分组
         * @param item
         * @returns {*}
         */

        $scope.specialGroupFn = function (item) {
            return $scope.specialDimensionsName[item.dimensionId]
        };


        $scope.specialTagsList = function (channelId) {
            $scope.specialTags = [];
            $scope.specialDimensionsName = {};

            ChannelManager.specialTagsList(channelId).then(function (result) {
                if (result.data.list) {
                    result.data.list.forEach(function (item) {
                        $scope.specialDimensionsName[item.dimensionId] = item.dimensionsName;

                        if (item.hasOwnProperty("list")) {
                            item.list.forEach(function (tag) {
                                $scope.specialTags.push({
                                    specialId: tag.specialId,
                                    dimensionId: tag.dimensionId,
                                    specialName: tag.specialName
                                })
                            })
                        }

                    })
                }


            })
        }

        $scope.removeFile = function ($index, item) {
            $scope.list.forEach(function (file) {
                if (file.file.webUrl == item.webUrl) {
                    $scope.list.splice($scope.list.indexOf(file), 1);
                }
            })
        }

        $scope.uploaderAudio = new FileUploader({
            alias: "uploadFile",
            queueLimit: 20,//文件个数
            // removeAfterUpload: true,//上传后删除文件 */
            filters: [{
                name: 'uploadFile',//后台接收字段
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    if (!/\.(mp3|MP3|AAC|aac)$/.test(item.name)) {
                        $scope.imageMsg = "最多只能上传" + 20 + "条mp3或者aac格式且每个小于" + 150 + "MB的音频";
                        $scope.image_a = true;
                        return false;
                    }
                    else if (item.size > 150 * 1024 * 1024||item.size < 0.5 * 1024 * 1024) {
                        $scope.imageMsg = "最多只能上传" + 20 + "条mp3或者aac格式且每个小于" + 150 + "MB的音频";
                        $scope.image_a = true;
                        return false
                    } else {
                        $scope.image_a = false;
                        return true;
                    }

                }
            }],
            onSuccessItem: function (fileItem, response, headers) {
                if (response.c == "s") {
                    fileItem.webUrl = response.fileVO.webUrl;

                    delete  response.c;
                    $scope.list.push({file: response.fileVO, audio: response.audioInfoVO});
                } else {
                    fileItem.isSuccess = 'uploadFail';

                }
            },
            url: api + "/cp/programs/audio",
            headers: {'X-Auth-Token': $scope.userInfo.token}
        })

        $scope.uploadAllAudio = function () {
            $scope.uploaderAudio.uploadAll();
        }






        $scope.myImage = '';
        $scope.myCroppedImage = '';

        var handleFileSelect = function (evt) {
            var file = evt.currentTarget.files[0];

            $scope.uploadCover(file);

        };

        setTimeout(function () {
            angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
        }, 1000)

        $scope.uploadCover = function (image) {
            if(image.type.indexOf("image")==-1){
                $scope.$apply($scope.errorImg='仅支持PNG/JPG/JPEG格式');
                return false;
            }else {
                $scope.$apply($scope.errorImg='');
            }
            var modalInstance = $uibModal.open({
                animation: true,
                backdrop:false,
                templateUrl: 'uploadCover.html',
                controller: 'coverManageController',
                resolve: {
                    params: function () {
                        return {image: image,coverType:"album"};
                    }
                }
            });
            modalInstance.result.then(function (result) {
                $("#fileInput").prop("value","");
                if (result.url) {
                    $scope.formData.albumCover = result.url;

                }

            })
        }




        $scope.submit = function () {
            $scope.disabled = true;
            var commTag = [];
            var specialTag = [];
            $scope.commonTagsSelected.forEach(function (item) {
                commTag.push(item.commtagId)
            })
            $scope.specialTagsSelected.forEach(function (item) {
                specialTag.push(item.specialId)
            })

          $scope.formData.categoryId= $scope.categorySelected.categoryId;
          $scope.formData.channelId= $scope.channelSelected.channelId;

            $scope.formData.commTag = commTag.join(",")
            $scope.formData.specialTag = specialTag.join(",")
            $scope.formData.keyword =$scope.formData.keyword? $scope.formData.keyword.split(","):[]
            $scope.formData.list = $scope.list;
            delete $scope.formData.duration;
            delete $scope.formData.cpId;
            delete $scope.formData.commList;
            delete $scope.formData.status;
            delete $scope.formData.specialList;
            delete $scope.formData.reviewStatus;
            AlbumManager.albumEdit(albumId, $scope.formData).then(function (result) {
                $scope.disabled = false;
                if (result.data.c == "s") {
                    $state.go("main.album", {}, {reload: true})
                }else {
                    $scope.formData.keyword = $scope.formData.keyword.join(",")
                    ImsErr.open({message:result.data.i}).then(function (a) {
                    })
                }
            })
        }

    }])

